#include <iostream>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>

typedef struct
{
    int res;
    int is_wait;           //判断条件
    pthread_cond_t cond;   //定义条件变量
    pthread_mutex_t mutex; //定义互斥锁
} Result;                  //将结果保存到Result中，然后从Result中获取结果

//线程同步
void *setfunc(void *arg)
{
    
    
    int i=1,sum=0;
    for(;i<=100;i++){
        sum+=i;

    }

   Result*res=(Result*)arg;

   //将结果放大炮res中
   res->res=sum;
   pthread_mutex_lock(&res->mutex);
    //判断获取结果是否准备好，如果为0说明还没准备好
    while(!res->is_wait){
        pthread_mutex_unlock(&res->mutex);
        usleep(100);
        pthread_mutex_lock(&res->mutex);
    }
   
    pthread_mutex_unlock(&res->mutex);
    //通知唤醒等待结果的线程
    pthread_cond_broadcast(&res->cond);

    return (void *)0;
}




void *getfunc(void *arg)
{
    Result*res=(Result*)arg;

    //对两个线程的判断条件进行保护
    pthread_mutex_lock(&res->mutex);
    //代表获取结果的线程已经准备好了
    res->is_wait=1;
    pthread_cond_wait(&res->cond,&res->mutex);


    //唤醒后
    pthread_mutex_unlock(&res->mutex);

    int res=res->res;
    std::cout<<"res:"<<res<<" id:"<<pthread_self()<<std::endl;



    return (void *)0;
}

int main()
{

    int err;
    pthread_t t1, t2;

    Result r;
    r.is_wait = 0;

    pthread_cond_init(&r.cond, NULL);

    pthread_mutex_init(&r.mutex, NULL);

    if ((err = pthread_create(&t1, NULL, setfunc, (void*)&r)) != 0)
    {

        perror("pthread_create error");
        exit(1);
    }

    if ((err = pthread_create(&t2, NULL, getfunc, (void*)&r)) != 0)
    {
        perror("pthread_create");
        exit(1);
    }

  

    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    
    pthread_cond_destroy(&r.cond);
    pthread_mutex_destroy(&r.mutex);
    return 0;
}
